package com.smarthome.common.httpwapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;

/**
 * http response处理器<p>
 * 接口中有handleResponse(HttpResponse response)方法。使用这个方法，用户完全不用关心http连接管理器。
 * 当使用ResponseHandler时，HttpClient会自动地将Http连接释放给Http管理器，即使http请求失败了或者抛出了异常。
 */
public class HttpResponseHandler implements ResponseHandler<HttpResponse>  {

    @Override
    public HttpResponse handleResponse(org.apache.http.HttpResponse response)
            throws ClientProtocolException, IOException {
        HttpResponse hr = new HttpResponse();
        try {
            hr.setStatusCode(response.getStatusLine().getStatusCode());
            hr.setBody(EntityUtils.toString(response.getEntity()));
            hr.setHeadersMap(resolveResponseHeader(response.getAllHeaders()));
            hr.setCookiesMap(resolveResponseCookie(response.getAllHeaders()));
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return hr;
    }
    
    /**
     * 解析返回消息头
     * @param headers {@link org.apache.http.Header} 键值对Hader对象
     * @return 键值对消息头Map
     */
    private static Map<String, String> resolveResponseHeader(Header[] headers) {
        if (headers == null || headers.length == 0) {
            return null;
        }
        Map<String, String> headersMap = new HashMap<String, String>();
        for (Header header : headers) {
            // Cookie头放在Cookie中resolveResponseCookie解析
            if (StringUtils.equalsIgnoreCase(HttpHeaders.SET_COOKIE, header.getName())) {
                continue;
            }
            headersMap.put(StringUtils.trim(header.getName()), StringUtils.trim(header.getValue()));
        }
        return headersMap;
    }

    /**
     * 解析返回消息头中的cookie
     * @param headers {@link org.apache.http.Header} 键值对Hader对象
     * @return 键值对消息头Map
     */
    private static Map<String, String> resolveResponseCookie(Header[] headers) {
        if (headers == null || headers.length == 0) {
            return null;
        }
        Map<String, String> cookiesMap = new HashMap<String, String>();
        for (Header header : headers) {
            // Cookie
            if (StringUtils.equalsIgnoreCase(HttpHeaders.SET_COOKIE, header.getName()) && StringUtils.isNotBlank(header.getValue())) {
                String[] cookieItemArray = header.getValue().split(";");
                if(cookieItemArray==null || cookieItemArray.length==0){
                    continue;
                }
                for (String cookieItem : cookieItemArray) {
                    if (StringUtils.isBlank(cookieItem)) {
                        continue;
                    }
                    String[] cookieItemValueArray = cookieItem.split("=");
                    if(cookieItemValueArray==null|| cookieItemValueArray.length==0 || cookieItemValueArray.length==1){
                        continue;
                    }
                    cookiesMap.put(StringUtils.trim(cookieItemValueArray[0]), StringUtils.trim(cookieItemValueArray[1]));
                }
                break;
            }
        }
        return cookiesMap;
    }

}
